//
//  YPickerView.m
//  jungoo
//
//  Created by Sinbad Fly on 8/22/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "YPickerView.h"

#define MIN_Y 1900
#define MAX_Y 2100

@implementation YPickerView

@synthesize year = _year;

#pragma mark - Private Method

-(void)awakeFromNib
{
    [super awakeFromNib];
    
    self.delegate = self;
    self.dataSource = self;
    
    [self selectToday];
}

- (NSString*)year
{
    return _year;
}

- (void)setYear:(NSString *)aYear
{    
    NSInteger index = [aYear integerValue];
    
    if (index >= MIN_Y && index <= MAX_Y) {
        index -= MIN_Y;
        
        [_year release];
        _year = [aYear retain];
    }
    else {        
        NSString *nowYear = [JGoUtility stringFromDate2:[NSDate date]];
        index = [nowYear integerValue];
        index -= MIN_Y;
        
        [_year release];
        _year = [nowYear retain];
    }
    
    [self selectRow:index inComponent:0 animated:NO];    
}

- (void)selectToday
{
    NSString *nowYear = [JGoUtility stringFromDate2:[NSDate date]];
    NSInteger index = [nowYear integerValue];
    index -= MIN_Y; 
    [self selectRow:index inComponent:0 animated:NO];
    
    [_year release];
    _year = [nowYear retain];
}

#pragma mark PickerView Delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return (MAX_Y - MIN_Y);
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return ([NSString stringWithFormat:@"%d",row + MIN_Y]);
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSString *newYear = [NSString stringWithFormat:@"%d",row + MIN_Y];
    [_year release];
    _year = [newYear retain];
}

@end
